import 'package:FlutterDemo/common/commons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

/// https://www.jianshu.com/p/b8f3aeda6551
/// BlocProvider 为 Bloc 的供应者，创建 Bloc 并供应给其子控件树；
///
class SampleBloc3Widget extends StatefulWidget {
  const SampleBloc3Widget({Key? key}) : super(key: key);

  @override
  _SampleBloc3WidgetState createState() => _SampleBloc3WidgetState();
}

class _SampleBloc3WidgetState extends State<SampleBloc3Widget> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => MyNumber3Bloc(),
      child: BlocBuilder<MyNumber3Bloc, int>(
        builder: (context, count) {
          return Container(
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.all(24),
                  child: Text(
                    "$count",
                    style: TextStyle(fontSize: 37),
                  ),
                ),
                buildCommonRaisedButton("+", 20.0, () {
                  context.read<MyNumber3Bloc>().add(MyNumber3Event.increment);
                }),
                buildCommonRaisedButton("-", 20.0, () {
                  context.read<MyNumber3Bloc>().add(MyNumber3Event.decrement);
                }),
              ],
            ),
          );
        },
      ),
    );
  }
}

enum MyNumber3Event { increment, decrement }

class MyNumber3Bloc extends Bloc<MyNumber3Event, int> {
  MyNumber3Bloc() : super(0);

  @override
  Stream<int> mapEventToState(MyNumber3Event event) async* {
    switch (event) {
      case MyNumber3Event.increment:
        yield state + 1;
        break;
      case MyNumber3Event.decrement:
        yield state - 1;
        break;
    }
  }
}
